package com.reebake.ideal.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.storage.entity.FileDetail;
import com.reebake.ideal.storage.service.FileDetailService;
import com.reebake.ideal.storage.service.FilePartRecorderService;
import com.reebake.ideal.storage.service.FileRecorderService;
import com.reebake.ideal.storage.util.StorageUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class FileRecorderServiceImpl implements FileRecorderService {
    private final FileDetailService fileDetailService;
    private final FilePartRecorderService filePartRecorderService;

    /**
     * 保存文件信息到数据库
     */
    @SneakyThrows
    @Override
    public boolean save(FileInfo info) {
        FileDetail detail = StorageUtil.toFileDetail(info);
        boolean b = fileDetailService.save(detail);
        if (b) {
            info.setId(detail.getFileDetailId());
        }
        return b;
    }

    /**
     * 更新文件记录，可以根据文件 ID 或 URL 来更新文件记录，
     * 主要用在手动分片上传文件-完成上传，作用是更新文件信息
     */
    @SneakyThrows
    @Override
    public void update(FileInfo info) {
        FileDetail detail = StorageUtil.toFileDetail(info);
        LambdaQueryWrapper<FileDetail> qw = new LambdaQueryWrapper<FileDetail>()
                .eq(detail.getUrl() != null, FileDetail::getUrl, detail.getUrl())
                .eq(detail.getFileDetailId() != null, FileDetail::getFileDetailId, detail.getFileDetailId());
        fileDetailService.update(detail, qw);
    }

    /**
     * 根据 url 查询文件信息
     */
    @SneakyThrows
    @Override
    public FileInfo getByUrl(String url) {
        return StorageUtil.toFileInfo(fileDetailService.getOne(new LambdaQueryWrapper<FileDetail>().eq(FileDetail::getUrl, url)));
    }

    /**
     * 根据 url 删除文件信息
     */
    @Override
    public boolean delete(String url) {
        fileDetailService.remove(new LambdaQueryWrapper<FileDetail>().eq(FileDetail::getUrl, url));
        return true;
    }

    /**
     * 保存文件分片信息
     * @param filePartInfo 文件分片信息
     */
    @Override
    public void saveFilePart(FilePartInfo filePartInfo) {
        filePartRecorderService.saveFilePart(filePartInfo);
    }

    /**
     * 删除文件分片信息
     */
    @Override
    public void deleteFilePartByUploadId(String uploadId) {
        filePartRecorderService.deleteFilePartByUploadId(uploadId);
    }

}
